package com.hadluo.qq.client.ui;

import com.alibaba.fastjson.JSON;
import com.hadluo.qq.client.event.MessageEvent;
import com.hadluo.qq.client.model.*;
import com.hadluo.qq.client.utils.Constants;
import com.hadluo.qq.client.utils.HttpClient;
import com.hadluo.qq.client.websocket.QQWebSocketClient;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.plaf.basic.BasicScrollBarUI;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.RoundRectangle2D;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;

public class GroupChatPanel extends JPanel implements QQWebSocketClient.MessageListener {
    private JTextArea inputArea;
    private JPanel chatHistoryPanel;
    private JScrollPane chatScrollPane;
    private JList<GroupMember> memberList;
    private DefaultListModel<GroupMember> memberListModel;
    private SimpleDateFormat timeFormat;
    QQWebSocketClient webSocketClient;
    private JPanel functionPanel;
    private JButton shakeButton;

    private Group group;
    private UserInfo currentUser;

    public GroupChatPanel(Group group, UserInfo currentUser) {
        this.group = group;
        this.currentUser = currentUser;
        this.timeFormat = new SimpleDateFormat("HH:mm:ss");
        initializeUI();
        QQWebSocketClient.getInstance().addMessageListener(this);

        loadGroupMembers();

        loadChatHistory();
    }

    private void initializeUI() {
        setLayout(new BorderLayout());
        setBackground(new Color(35, 35, 35));

        // 创建左侧聊天面板
        JPanel leftPanel = new JPanel(new BorderLayout());
        leftPanel.setBackground(new Color(35, 35, 35));

        // 添加群信息头部
        leftPanel.add(createHeaderPanel(), BorderLayout.NORTH);

        // 添加聊天历史记录
        leftPanel.add(createChatHistoryPanel(), BorderLayout.CENTER);

        // 添加输入面板
        leftPanel.add(createInputPanel(), BorderLayout.SOUTH);

        // 创建右侧成员列表面板
        JPanel rightPanel = createMemberListPanel();

        // 使用分隔面板组合左右两部分
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, rightPanel);
        splitPane.setDividerLocation(600);
        splitPane.setDividerSize(1);
        splitPane.setBorder(null);

        add(splitPane);
    }

    private JPanel createHeaderPanel() {
        JPanel headerPanel = new JPanel(new BorderLayout());
        headerPanel.setBackground(new Color(45, 45, 45));
        headerPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(60, 60, 60)),
                new EmptyBorder(10, 15, 10, 15)
        ));

        // 创建群信息面板
        JPanel infoPanel = new JPanel(new GridLayout(2, 1, 0, 5));
        infoPanel.setBackground(new Color(45, 45, 45));

        // 群名称
        JLabel groupNameLabel = new JLabel("测试群组");
        groupNameLabel.setForeground(Color.WHITE);
        groupNameLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));

        // 群描述
        JLabel descriptionLabel = new JLabel("这是一个测试群组的描述信息");
        descriptionLabel.setForeground(new Color(153, 153, 153));
        descriptionLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));

        infoPanel.add(groupNameLabel);
        infoPanel.add(descriptionLabel);

        headerPanel.add(infoPanel, BorderLayout.CENTER);

        return headerPanel;
    }

    private JScrollPane createChatHistoryPanel() {
        chatHistoryPanel = new JPanel();
        chatHistoryPanel.setLayout(new BoxLayout(chatHistoryPanel, BoxLayout.Y_AXIS));
        chatHistoryPanel.setBackground(new Color(35, 35, 35));

        chatScrollPane = new JScrollPane(chatHistoryPanel);
        chatScrollPane.setBorder(null);
        chatScrollPane.getVerticalScrollBar().setUI(new CustomScrollBarUI());
        chatScrollPane.setBackground(new Color(35, 35, 35));
        chatScrollPane.getViewport().setBackground(new Color(35, 35, 35));

        return chatScrollPane;
    }

    private JPanel createInputPanel() {
        JPanel inputPanel = new JPanel(new BorderLayout());
        inputPanel.setBackground(new Color(45, 45, 45));
        inputPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(60, 60, 60)),
                new EmptyBorder(15, 15, 15, 15)
        ));

        // 创建功能按钮面板
        JPanel functionPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 8, 0));
        functionPanel.setBackground(new Color(45, 45, 45));

//        JButton emojiButton = createFunctionButton("表情");
//        emojiButton.addActionListener(e -> openEmojiChooser());
        JButton imageButton = createFunctionButton("图片");
        imageButton.addActionListener(e -> openImageChooser());
//        shakeButton = createFunctionButton("抖动"); // 新增抖动按钮
//        shakeButton.addActionListener(e -> sendGroupShakeMessage());
//        functionPanel.add(shakeButton);
//        functionPanel.add(emojiButton);
        functionPanel.add(imageButton);

        // 创建输入区域
        inputArea = new JTextArea();
        inputArea.setBackground(new Color(35, 35, 35));
        inputArea.setForeground(Color.WHITE);
        inputArea.setCaretColor(Color.WHITE);
        inputArea.setLineWrap(true);
        inputArea.setWrapStyleWord(true);
        inputArea.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        inputArea.setRows(3);
        inputArea.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));

        JScrollPane inputScrollPane = new JScrollPane(inputArea);
        inputScrollPane.setBorder(BorderFactory.createLineBorder(new Color(60, 60, 60)));
        inputScrollPane.getVerticalScrollBar().setUI(new CustomScrollBarUI());
        inputScrollPane.setBackground(new Color(35, 35, 35));

        // 创建发送按钮
        JButton sendButton = new JButton("发送");
        sendButton.setBackground(new Color(0, 132, 255));
        sendButton.setForeground(Color.WHITE);
        sendButton.setFocusPainted(false);
        sendButton.setBorder(BorderFactory.createEmptyBorder(8, 20, 8, 20));
        sendButton.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        sendButton.addActionListener(e -> sendMessage());
        // 添加鼠标悬停效果
        sendButton.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent evt) {
                sendButton.setBackground(new Color(0, 122, 235));
            }

            public void mouseExited(MouseEvent evt) {
                sendButton.setBackground(new Color(0, 132, 255));
            }
        });

        // 创建底部面板
        JPanel bottomPanel = new JPanel(new BorderLayout(5, 0));
        bottomPanel.setBackground(new Color(45, 45, 45));
        bottomPanel.add(inputScrollPane, BorderLayout.CENTER);
        bottomPanel.add(sendButton, BorderLayout.EAST);

        inputPanel.add(functionPanel, BorderLayout.NORTH);
        inputPanel.add(bottomPanel, BorderLayout.CENTER);

        return inputPanel;
    }

    private JButton createFunctionButton(String text) {
        JButton button = new JButton(text);
        button.setBackground(new Color(245, 245, 245));
        button.setForeground(new Color(51, 51, 51));
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(230, 230, 230)),
                BorderFactory.createEmptyBorder(5, 10, 5, 10)
        ));

        button.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(235, 235, 235));
            }

            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(new Color(245, 245, 245));
            }
        });

        return button;
    }

    private void sendGroupShakeMessage() {
        GroupMessage message = new GroupMessage();
        message.setSenderId(Long.parseLong(currentUser.getQqNumber()));
        message.setGroupId(group.getId());
        message.setType(Message.TYPE_SHAKE);
        message.setContent("抖动消息");

        webSocketClient.sendGroupMessage(message, currentUser);
    }

    private JButton creatoneFunctionButton(String text) {
        JButton button = new JButton(text);
        button.setBackground(new Color(245, 245, 245));
        button.setForeground(new Color(51, 51, 51));
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(230, 230, 230)),
                BorderFactory.createEmptyBorder(5, 10, 5, 10)
        ));

        button.addMouseListener(new MouseAdapter() {
            public void mouseEntered(MouseEvent evt) {
                button.setBackground(new Color(235, 235, 235));
            }

            public void mouseExited(MouseEvent evt) {
                button.setBackground(new Color(245, 245, 245));
            }
        });

        return button;
    }

    private String getRoleName(String role) {
        switch (role) {
            case "2":
                return "群主";
            case "1":
                return "管理员";
            case "0":
                return "成员";
            default:
                return "成员";
        }
    }

    private JPanel createMemberListPanel() {
        JPanel memberPanel = new JPanel(new BorderLayout());
        memberPanel.setBackground(new Color(35, 35, 35));
        memberPanel.setBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, new Color(60, 60, 60)));

        // 创建标题
        JLabel titleLabel = new JLabel("群成员");
        titleLabel.setForeground(Color.WHITE);
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        titleLabel.setBorder(new EmptyBorder(10, 15, 10, 15));

        // 创建成员列表
        memberListModel = new DefaultListModel<>();
        memberList = new JList<>(memberListModel);
        memberList.setBackground(new Color(35, 35, 35));
        memberList.setCellRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index,
                                                          boolean isSelected, boolean cellHasFocus) {
                GroupMember member = (GroupMember) value;
                JPanel panel = new JPanel(new BorderLayout(10, 0));
                panel.setBackground(isSelected ? new Color(45, 45, 45) : new Color(35, 35, 35));
                panel.setBorder(new EmptyBorder(5, 10, 5, 10));

                // 创建头像标签
                JLabel avatarLabel = new JLabel();
                avatarLabel.setPreferredSize(new Dimension(30, 30));
                avatarLabel.setBackground(new Color(60, 60, 60));
                avatarLabel.setOpaque(true);
                avatarLabel.setHorizontalAlignment(SwingConstants.CENTER);

                // 设置头像
                String avatarUrl = member.getAvatar();
                if (avatarUrl != null && !avatarUrl.isEmpty()) {
                    try {
                        if (!avatarUrl.startsWith("http")) {
                            avatarUrl = "http://"+ Constants.SERVER_HOST+":8080" + avatarUrl;
                        }
                        ImageIcon imageIcon = new ImageIcon(new URL(avatarUrl));
                        Image image = imageIcon.getImage().getScaledInstance(30, 30, Image.SCALE_SMOOTH);
                        avatarLabel.setIcon(new ImageIcon(image));
                    } catch (Exception e) {
                        // 如果加载失败，显示首字母
                        avatarLabel.setText(member.getNickname().substring(0, 1));
                        avatarLabel.setForeground(Color.WHITE);
                        avatarLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
                    }
                } else {
                    // 如果没有头像，显示首字母
                    avatarLabel.setText(member.getNickname().substring(0, 1));
                    avatarLabel.setForeground(Color.WHITE);
                    avatarLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
                }

                // 创建成员信息标签
                JLabel infoLabel = new JLabel(getRoleName(member.getRole()) + " - " + member.getNickname());
                infoLabel.setForeground(Color.WHITE);
                infoLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));

                panel.add(avatarLabel, BorderLayout.WEST);
                panel.add(infoLabel, BorderLayout.CENTER);

                return panel;
            }
        });

        JScrollPane scrollPane = new JScrollPane(memberList);
        scrollPane.setBorder(null);
        scrollPane.getVerticalScrollBar().setUI(new CustomScrollBarUI());

        memberPanel.add(titleLabel, BorderLayout.NORTH);
        memberPanel.add(scrollPane, BorderLayout.CENTER);

        return memberPanel;
    }

    private void loadGroupMembers() {
        new Thread(() -> {
            try {
                GroupMemberResponse response = HttpClient.getGroupMembers(group.getId());
                if (response.isSuccess()) {
                    SwingUtilities.invokeLater(() -> {
                        memberListModel.clear();
                        for (GroupMember member : response.getMembers()) {
                            memberListModel.addElement(member);
                        }
                    });
                } else {
                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(this,
                                "加载群成员失败: " + response.getMessage(),
                                "错误",
                                JOptionPane.ERROR_MESSAGE);
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(this,
                            "加载群成员失败: " + e.getMessage(),
                            "错误",
                            JOptionPane.ERROR_MESSAGE);
                });
            }
        }).start();
    }

    @Override
    public void onMessageReceived(MessageEvent event) {
        GroupMessage message = event.getGroupMessage();
        if (message != null && Message.TYPE_SHAKE.equals(message.getType())) {
            // 实现抖动效果
            shakeWindow();
        }
        SwingUtilities.invokeLater(() -> {
            // 播放提示音
            Toolkit.getDefaultToolkit().beep();
            // 根据消息类型选择不同的显示方式
            addMessageToPanel(message);
        });
    }

    private void shakeWindow() {
        JFrame frame = (JFrame) SwingUtilities.getWindowAncestor(this);
        Point originalLocation = frame.getLocation();
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            int x = originalLocation.x + random.nextInt(10) - 5;
            int y = originalLocation.y + random.nextInt(10) - 5;
            frame.setLocation(x, y);
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        frame.setLocation(originalLocation);
    }

//    private void addMessage(String message, boolean isCurrentUser) {
//        JPanel messagePanel = new JPanel(new FlowLayout(isCurrentUser ? FlowLayout.RIGHT : FlowLayout.LEFT, 10, 0));
//        messagePanel.setBackground(new Color(35, 35, 35));
//        messagePanel.setBorder(new EmptyBorder(5, 15, 5, 15));
//
//        // 创建消息气泡
//        JPanel bubblePanel = new JPanel(new BorderLayout());
//        bubblePanel.setBackground(isCurrentUser ? new Color(0, 132, 255) : new Color(45, 45, 45));
//        bubblePanel.setBorder(BorderFactory.createEmptyBorder(10, 15, 10, 15));
//
//        JLabel messageLabel = new JLabel(message);
//        messageLabel.setForeground(Color.WHITE);
//        bubblePanel.add(messageLabel);
//
//        messagePanel.add(bubblePanel);
//        chatHistoryPanel.add(messagePanel);
//        chatHistoryPanel.revalidate();
//        chatHistoryPanel.repaint();
//
//        // 自动滚动到底部
//        SwingUtilities.invokeLater(() -> {
//            JScrollBar vertical = chatScrollPane.getVerticalScrollBar();
//            vertical.setValue(vertical.getMaximum());
//        });
//    }

    private static class CustomScrollBarUI extends BasicScrollBarUI {
        @Override
        protected void configureScrollBarColors() {
            this.thumbColor = new Color(100, 100, 100);
            this.trackColor = new Color(45, 45, 45);
        }

        @Override
        protected JButton createDecreaseButton(int orientation) {
            return createZeroButton();
        }

        @Override
        protected JButton createIncreaseButton(int orientation) {
            return createZeroButton();
        }

        private JButton createZeroButton() {
            JButton button = new JButton();
            button.setPreferredSize(new Dimension(0, 0));
            return button;
        }
    }


    private void sendMessage() {
        String content = inputArea.getText().trim();
        if (!content.isEmpty()) {
            GroupMessage message = new GroupMessage();
            message.setGroupId(group.getId());
            message.setSenderId(Long.parseLong(currentUser.getQqNumber()));
            message.setContent(content);
            message.setType("group-text"); // 文本消息
            message.setCreateTime(new Date());

            QQWebSocketClient.getInstance().sendGroupMessage(message,currentUser);
            message.setUser(currentUser);
            addMessageToPanel(message);
            inputArea.setText("");
        }
    }

    private void loadChatHistory() {
        try {
            GroupChatHistoryResponse response = HttpClient.getGroupChatHistory(group.getId().toString());
            if (response.isSuccess()) {
                for (GroupMessage message : response.getMessages()) {
                    addMessageToPanel(message);
                }
                // 滚动到最新消息
                SwingUtilities.invokeLater(() -> {
                    JScrollBar vertical = chatScrollPane.getVerticalScrollBar();
                    vertical.setValue(vertical.getMaximum());
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载历史消息失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void addMessageToPanel(GroupMessage message) {
        boolean isCurrentUser = message.getSenderId() == Long.parseLong(currentUser.getQqNumber());

        if(message.getType().contains("image")){
            addImageMessage(message);
            return ;
        }

        JPanel messagePanel = new JPanel(new FlowLayout(isCurrentUser ? FlowLayout.RIGHT : FlowLayout.LEFT, 10, 0));
        messagePanel.setBackground(new Color(35, 35, 35));
        messagePanel.setBorder(new EmptyBorder(5, 15, 5, 15));

        // 创建头像标签
        JLabel avatarLabel = new JLabel();
        avatarLabel.setPreferredSize(new Dimension(40, 40));
        avatarLabel.setBackground(new Color(35, 35, 35));
        avatarLabel.setOpaque(true);

        // 设置头像
        String avatarUrl = message.getUser().getAvatar();
        if (avatarUrl != null && !avatarUrl.isEmpty()) {
            try {
                if (!avatarUrl.startsWith("http")) {
                    avatarUrl = "http://"+Constants.SERVER_HOST+":8080" + avatarUrl;
                }
                ImageIcon imageIcon = new ImageIcon(new URL(avatarUrl));
                Image image = imageIcon.getImage().getScaledInstance(40, 40, Image.SCALE_SMOOTH);
                avatarLabel.setIcon(new ImageIcon(image));
            } catch (Exception e) {
                String avatarText =message.getUser().getNickname().substring(0, 1);
                avatarLabel.setText(avatarText);
                avatarLabel.setHorizontalAlignment(SwingConstants.CENTER);
                avatarLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
                avatarLabel.setForeground(Color.WHITE);
            }
        } else {
            String avatarText =message.getUser().getNickname().substring(0, 1);
            avatarLabel.setText(avatarText);
            avatarLabel.setHorizontalAlignment(SwingConstants.CENTER);
            avatarLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
            avatarLabel.setForeground(Color.WHITE);
        }

        // 创建消息内容面板
        JPanel contentPanel = new JPanel(new BorderLayout(0, 3));
        contentPanel.setBackground(new Color(35, 35, 35));
        contentPanel.setOpaque(false);

        // 创建发送者昵称标签
        if (!isCurrentUser) {
            JLabel nicknameLabel = new JLabel(message.getUser().getNickname());
            nicknameLabel.setForeground(new Color(153, 153, 153));
            nicknameLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
            nicknameLabel.setBorder(new EmptyBorder(0, 8, 2, 0));
            contentPanel.add(nicknameLabel, BorderLayout.NORTH);
        }

        // 创建消息气泡
        JPanel bubblePanel = new JPanel(new BorderLayout());
        bubblePanel.setBackground(isCurrentUser ? new Color(0, 132, 255) : new Color(45, 45, 45));
        bubblePanel.setBorder(BorderFactory.createEmptyBorder(10, 15, 10, 15));

        JLabel messageLabel = new JLabel(message.getContent());
        messageLabel.setForeground(Color.WHITE);
        bubblePanel.add(messageLabel);

        // 创建时间标签
        JLabel timeLabel = new JLabel(timeFormat.format(message.getCreateTime()));
        timeLabel.setForeground(new Color(153, 153, 153));
        timeLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        timeLabel.setBorder(new EmptyBorder(2, isCurrentUser ? 0 : 8, 0, isCurrentUser ? 8 : 0));
        contentPanel.add(timeLabel, BorderLayout.SOUTH);

        contentPanel.add(bubblePanel, BorderLayout.CENTER);

        // 根据是否为当前用户设置布局
        if (isCurrentUser) {
            messagePanel.add(contentPanel);
            messagePanel.add(avatarLabel);
        } else {
            messagePanel.add(avatarLabel);
            messagePanel.add(contentPanel);
        }

        chatHistoryPanel.add(messagePanel);
        chatHistoryPanel.revalidate();
        chatHistoryPanel.repaint();

        // 自动滚动到底部
        SwingUtilities.invokeLater(() -> {
            JScrollBar vertical = chatScrollPane.getVerticalScrollBar();
            vertical.setValue(vertical.getMaximum());
        });
    }

    private void openEmojiChooser() {
        // 创建表情选择面板
        JDialog emojiDialog = new JDialog((Frame) SwingUtilities.getWindowAncestor(this), "选择表情", true);
        emojiDialog.setLayout(new BorderLayout());

        // 创建表情网格面板
        JPanel emojiPanel = new JPanel(new GridLayout(3, 5, 5, 5));
        emojiPanel.setBackground(new Color(45, 45, 45));
        emojiPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 定义表情列表
        String[] emojis = {"😊", "😂", "🤣", "😅", "😆", "😍", "😘", "🥰", "😎", "🤔", "😏", "😣", "😥", "😪"};

        // 为每个表情创建按钮
        for (String emoji : emojis) {
            JButton emojiButton = new JButton(emoji);
            emojiButton.setFont(new Font("Segoe UI Emoji", Font.PLAIN, 24));
            emojiButton.setBackground(new Color(35, 35, 35));
            emojiButton.setForeground(Color.WHITE);
            emojiButton.setBorder(BorderFactory.createLineBorder(new Color(60, 60, 60)));
            emojiButton.setFocusPainted(false);

            // 添加鼠标悬停效果
            emojiButton.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseEntered(java.awt.event.MouseEvent evt) {
                    emojiButton.setBackground(new Color(55, 55, 55));
                }

                public void mouseExited(java.awt.event.MouseEvent evt) {
                    emojiButton.setBackground(new Color(35, 35, 35));
                }
            });

            // 添加点击事件
            emojiButton.addActionListener(e -> {
                inputArea.insert(emoji, inputArea.getCaretPosition());
                emojiDialog.dispose();
            });

            emojiPanel.add(emojiButton);
        }

        emojiDialog.add(emojiPanel, BorderLayout.CENTER);
        emojiDialog.pack();
        emojiDialog.setLocationRelativeTo(this);
        emojiDialog.setVisible(true);
    }

    private void openImageChooser() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileFilter(new FileNameExtensionFilter("图片文件", "jpg", "jpeg", "png", "gif"));

        if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            try {
                // 检查文件大小（限制为5MB）
                if (selectedFile.length() > 5 * 1024 * 1024) {
                    JOptionPane.showMessageDialog(this, "图片大小不能超过5MB", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                // 创建文件上传请求
                String uploadUrl = "http://"+Constants.SERVER_HOST+":8080/api/file/upload";
                HttpURLConnection conn = (HttpURLConnection) new URL(uploadUrl).openConnection();
                conn.setRequestMethod("POST");
                String boundary = "----WebKitFormBoundary" + System.currentTimeMillis();
                conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
                conn.setDoOutput(true);

                try (OutputStream os = conn.getOutputStream()) {
                    // 写入文件数据
                    os.write(("--" + boundary + "\r\n").getBytes());
                    String g = "Content-Disposition: form-data; name=\"file\"; filename=\""
                            + selectedFile.getName() + "\"\r\n";
                    os.write(g.getBytes());
                    os.write("Content-Type: image/jpeg\r\n\r\n".getBytes());
                    Files.copy(selectedFile.toPath(), os);
                    os.write("\r\n".getBytes());
                    os.write(("--" + boundary + "--\r\n").getBytes());
                }

                // 获取响应
                int responseCode = conn.getResponseCode();
                if (responseCode == 200) {
                    // 读取响应内容
                    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String response = in.readLine();
                    in.close();

                    // 解析响应获取图片URL
                    Map<String, Object> result = JSON.parseObject(response);
                    String imageUrl = (String) result.get("url");

                    // 创建图片消息
                    GroupMessage message = new GroupMessage();
                    message.setGroupId(group.getId());
                    message.setSenderId(Long.parseLong(currentUser.getQqNumber()));
                    message.setContent(imageUrl); // 使用图片URL而不是Base64
                    message.setType("group-image"); // 图片消息
                    message.setCreateTime(new Date());
                    message.setUser(currentUser);
                    // 发送消息
                    QQWebSocketClient.getInstance().sendGroupMessage(message , currentUser);
                    // 在聊天面板中显示图片
//                    ImageIcon imageIcon = new ImageIcon(selectedFile.getPath());
//                    Image scaledImage = imageIcon.getImage().getScaledInstance(200, -1, Image.SCALE_SMOOTH);
//                    addImageMessage(new ImageIcon(scaledImage), true);
                    addImageMessage(message);
                } else {
                    throw new IOException("服务器返回错误代码：" + responseCode);
                }

            } catch (IOException e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, "发送图片失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    private void addImageMessage(GroupMessage groupMessage) {
        boolean isCurrentUser = groupMessage.getSenderId().toString().equals(currentUser.getQqNumber()) ;
        String imageUrl = groupMessage.getContent();
        try {
            // 确保URL包含完整的服务器地址前缀
            if (!imageUrl.startsWith("http")) {
                imageUrl = "http://"+Constants.SERVER_HOST+":8080" + imageUrl;
            }
            // 从URL加载图片
            ImageIcon imageIcon = new ImageIcon(new URL(imageUrl));

            // 调整图片大小
            Image image = imageIcon.getImage();
            int maxWidth = 300;
            int maxHeight = 300;

            int width = image.getWidth(null);
            int height = image.getHeight(null);

            if (width > maxWidth || height > maxHeight) {
                double scale = Math.min((double) maxWidth / width, (double) maxHeight / height);
                width = (int) (width * scale);
                height = (int) (height * scale);
            }

            Image scaledImage = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            ImageIcon scaledIcon = new ImageIcon(scaledImage);

            // 创建图片标签
            JLabel imageLabel = new JLabel(scaledIcon);
            imageLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

            // 创建消息面板
            JPanel messagePanel = new JPanel(new FlowLayout(isCurrentUser ? FlowLayout.RIGHT : FlowLayout.LEFT, 10, 0));
            messagePanel.setBackground(new Color(35, 35, 35));
            messagePanel.setBorder(new EmptyBorder(5, 15, 5, 15));

            // 创建头像标签
            JLabel avatarLabel = new JLabel();
            avatarLabel.setPreferredSize(new Dimension(40, 40));
            avatarLabel.setBackground(new Color(35, 35, 35));
            avatarLabel.setOpaque(true);

            // 设置头像
            String avatarUrl =  groupMessage.getUser().getAvatar();
            if (avatarUrl != null && !avatarUrl.isEmpty()) {
                try {
                    if (!avatarUrl.startsWith("http")) {
                        avatarUrl = "http://"+Constants.SERVER_HOST+":8080" + avatarUrl;
                    }
                    ImageIcon avatar = new ImageIcon(new URL(avatarUrl));
                    Image avatarImage = avatar.getImage().getScaledInstance(40, 40, Image.SCALE_SMOOTH);
                    avatarLabel.setIcon(new ImageIcon(avatarImage));
                } catch (Exception e) {
                    String avatarText = groupMessage.getUser().getNickname().substring(0, 1);
                    avatarLabel.setText(avatarText);
                    avatarLabel.setHorizontalAlignment(SwingConstants.CENTER);
                    avatarLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
                    avatarLabel.setForeground(new Color(51, 51, 51));
                }
            }

            // 创建内容面板
            JPanel contentPanel = new JPanel(new BorderLayout(0, 3));
            contentPanel.setBackground(new Color(35, 35, 35));
            contentPanel.setOpaque(false);

            // 创建时间标签
            JLabel timeLabel = new JLabel(timeFormat.format(new Date()));
            timeLabel.setForeground(new Color(153, 153, 153));
            timeLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
            timeLabel.setBorder(new EmptyBorder(0, isCurrentUser ? 0 : 8, 2, isCurrentUser ? 8 : 0));

            // 创建气泡面板
            JPanel bubblePanel = new JPanel() {
                @Override
                protected void paintComponent(Graphics g) {
                    Graphics2D g2 = (Graphics2D) g.create();
                    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                    int width = getWidth();
                    int height = getHeight();
                    int radius = 15;

                    GradientPaint gradient;
                    if (isCurrentUser) {
                        gradient = new GradientPaint(
                                0, 0, new Color(0, 132, 255),
                                width, height, new Color(0, 122, 235)
                        );
                    } else {
                        gradient = new GradientPaint(
                                0, 0, new Color(45, 45, 45),
                                width, height, new Color(55, 55, 55)
                        );
                    }

                    g2.setColor(new Color(0, 0, 0, 30));
                    g2.fillRoundRect(2, 2, width - 2, height - 2, radius, radius);
                    g2.setColor(new Color(0, 0, 0, 15));
                    g2.fillRoundRect(1, 1, width - 1, height - 1, radius, radius);

                    RoundRectangle2D bubble = new RoundRectangle2D.Float(0, 0, width - 3, height - 3, radius, radius);
                    g2.setPaint(gradient);
                    g2.fill(bubble);

                    g2.dispose();
                }
            };
            bubblePanel.setOpaque(false);
            bubblePanel.setLayout(new BorderLayout());
            bubblePanel.add(imageLabel, BorderLayout.CENTER);

            // 组装消息面板
            contentPanel.add(timeLabel, BorderLayout.NORTH);
            contentPanel.add(bubblePanel, BorderLayout.CENTER);

            if (isCurrentUser) {
                messagePanel.add(contentPanel);
                messagePanel.add(avatarLabel);
            } else {
                messagePanel.add(avatarLabel);
                messagePanel.add(contentPanel);
            }

            // 添加消息到聊天历史面板
            chatHistoryPanel.add(messagePanel);
            chatHistoryPanel.revalidate();

            // 自动滚动到底部
            SwingUtilities.invokeLater(() -> {
                JScrollBar vertical = chatScrollPane.getVerticalScrollBar();
                vertical.setValue(vertical.getMaximum());
            });
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "图片显示失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}